<!--
 * @Description: 富文本组件
 * @Author: Zhanghan
 * @Date: 2024-12-06 15:28:08
 * @LastEditTime: 2024-12-10 09:55:19
 * @LastEditors: Zhanghan
-->
<template>
  <div style="border: 1px solid #ccc" class="w-full h-full">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="'default'"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="'default'"
      @onChange="handleChange"
      @onCreated="handleCreated"
    />
  </div>
</template>
<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

defineOptions({ name: "MyEditor" });

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("<p>hello</p>");

const emits = defineEmits(["change"]);

// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = "<p>模拟 Ajax 异步设置内容</p>";
  }, 1500);
});

const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

// 编辑器创建完毕时的回调函数
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

// 编辑器 Change 时的回调函数
const handleChange = (editor: any) => {
  const data = {
    html: editor.getHtml() == "<p><br></p>" ? "" : editor.getHtml(),
    text: editor.getText(),
  };
  console.log(data);

  emits("change", data);
};
</script>
